package com.tjf.traffic.utils;

import android.annotation.SuppressLint;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.RemoteException;
import android.telephony.TelephonyManager;

import androidx.annotation.RequiresApi;

import com.tjf.traffic.bean.TrafficBean;


/**
 * @author: tjf
 * @date: 2022-12-10
 * @desc： NetworkStatsHelper 流量查询辅助类
 *
 * <p> 使用方式
 * * NetworkStatsManager networkStatsManager = (NetworkStatsManager) getSystemService(NETWORK_STATS_SERVICE);
 * * NetworkStatsHelper helper = new NetworkStatsHelper(networkStatsManager);
 * </p>
 */
@RequiresApi(api = Build.VERSION_CODES.M)
public class NetworkStatsHelper {

    NetworkStatsManager networkStatsManager;
    int packageUid;

    public void setPackageUid(int packageUid) {
        this.packageUid = packageUid;
    }

    public NetworkStatsHelper(NetworkStatsManager networkStatsManager) {
        this.networkStatsManager = networkStatsManager;
    }

    public NetworkStatsHelper(NetworkStatsManager networkStatsManager, int packageUid) {
        this.networkStatsManager = networkStatsManager;
        this.packageUid = packageUid;
    }


    /**
     * 获取 所有移动使用流量信息
     *
     * @param context       上下文
     * @param isDayAndMonth 是否是当天还是当月
     * @return 返回 当天 还是当月的流量信息
     */
    public TrafficBean getAllDay_MonthMobileInfo(Context context, boolean isDayAndMonth) {
        TrafficBean trafficBean = new TrafficBean();
        NetworkStats.Bucket bucket;
        try {
            bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
                    getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
                    isDayAndMonth ? DateUtil.getTimesmorning() :DateUtil. getTimesMonthmorning(),
                    System.currentTimeMillis());
        } catch (RemoteException e) {
            return trafficBean;

        }

        trafficBean.setRxBytes(bucket.getRxBytes());
        trafficBean.setTxBytes(bucket.getTxBytes());
        trafficBean.setTotalData(bucket.getTxBytes() + bucket.getRxBytes());


        return trafficBean;
    }

    /**
     * 获取所有应用一天使用的移动流量信息
     *
     * @param context   上下文
     * @param startTime 开始时间
     * @return 流量信息
     */
    public TrafficBean getOneDayMobileInfo(Context context, long startTime) {
        TrafficBean trafficBean = new TrafficBean();
        NetworkStats.Bucket bucket;
        try {
            bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
                    getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
                    startTime,
                    startTime + 86400000
            );


            trafficBean.setRxBytes(bucket.getRxBytes());
            trafficBean.setTxBytes(bucket.getTxBytes());
            trafficBean.setTotalData(bucket.getTxBytes() + bucket.getRxBytes());

        } catch (RemoteException e) {
            return trafficBean;

        }
        return trafficBean;
    }

    /**
     * 获取今日 或者今月的 应用 的实时流量使用情况
     *
     * @param context       上下文
     * @param isDayAndMonth 是否是今天还是今月
     * @return 获取今日 或者今月的流量使用情况
     */
    public TrafficBean getSummaryTrafficMobile(Context context, boolean isDayAndMonth) {
        TrafficBean trafficBean = new TrafficBean();
        trafficBean.setUid(packageUid + "");
        NetworkStats networkStats = null;

        try {
            networkStats = networkStatsManager.querySummary(
                    ConnectivityManager.TYPE_MOBILE,
                    getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
                    isDayAndMonth ? DateUtil.getTimesmorning() :DateUtil. getTimesMonthmorning(),
                    System.currentTimeMillis());


            long mobileTraffic = 0;//
            long mobileRx = 0;
            long mobileTx = 0;
            NetworkStats.Bucket bucket = new NetworkStats.Bucket();
            do {
                networkStats.getNextBucket(bucket);
                int summaryUid = bucket.getUid();
                if (packageUid == summaryUid) {

                    mobileTx += bucket.getTxBytes();
                    mobileRx += bucket.getRxBytes();
                }
            } while (networkStats.hasNextBucket());
            mobileTraffic = mobileRx + mobileTx;

            trafficBean.setTxBytes(mobileTx);
            trafficBean.setRxBytes(mobileRx);
            trafficBean.setTotalData(mobileTraffic);


        } catch (RemoteException e) {
            e.printStackTrace();
        } finally {
            if (networkStats != null) {
                networkStats.close();
            }
        }


        return trafficBean;
    }

    /**
     * 获取用户id android 10 以后获取不了 传null 即可
     * 需要权限
     * <uses-permission android:name="android.permission.READ_PHONE_STATE" />
     *
     * @param context     上下文
     * @param networkType 网络类型
     * @return null
     */
    @SuppressLint("MissingPermission")
    private String getSubscriberId(Context context, int networkType) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return null;
        }

        if (ConnectivityManager.TYPE_MOBILE == networkType) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getSubscriberId();
        }
        return null;
    }


}
